import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Types } from '../Schema/Types.schema'
import { Model } from 'mongoose'
import { Document, Types as MongooseTypes } from 'mongoose';
interface TypeDocument {
    _id: MongooseTypes.ObjectId;
    title: string;
    prent?: MongooseTypes.ObjectId;
    children?: TypeDocument[];
}
@Injectable()
export class TypesService {
    constructor(@InjectModel(Types.name) private TypesModel: Model<Types>) { }
    async gettypes(res) {
        // 从数据库中获取所有数据
        const result: TypeDocument[] = await this.TypesModel.find().lean().exec();
        // 创建一个以 _id 为键的对象，并初始化 children 属性
        const obj: { [key: string]: TypeDocument & { children?: TypeDocument[] } } = {};
        result.forEach(item => {
            obj[item._id.toString()] = { ...item, children: [] };
        });
        // 构建最终的数据树结构
        const data: TypeDocument[] = [];
        result.forEach(item => {
            if (!item.prent) {
                // 如果没有父级，则为根节点
                data.push(obj[item._id.toString()]);
            } else {
                // 添加到对应的父节点下
                const parentKey = item.prent.toString();
                if (obj[parentKey]) {
                    obj[parentKey].children!.push(obj[item._id.toString()]);
                }
            }
        });
        // 返回构建好的数据
        res.send({
            code: 200,
            data
        });

    }
    add(req, res) {
        this.TypesModel.create(req.body)
        let data = this.gettypes(res)
        res.send('添加成功')
    }
    async get(req, res) {
        let { title } = req.body
        console.log(req.body);
        let data = await this.TypesModel.find({ title: { $regex: title } })
        res.send({
            code: 200,
            data
        })
    }
    async delete(req, res) {
        await this.TypesModel.deleteMany({ _id: req.body._id });
        await this.TypesModel.deleteMany({ prent: req.body._id });
        res.send({
            code: 200,
            message: '删除成功'
        })
    }
    async update(req, res) {
        console.log(req.body);

        await this.TypesModel.updateOne({ _id: req.body._id }, req.body)
        res.send({
            code: 200,
            message: '更新成功'
        })
    }
}